package vn.gq.udv.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class IOUtils {
	
	public static String convertStreamToString(InputStream is) {
		StringBuilder output = new StringBuilder();
		int byteRead = 0;
		byte[] buffer = new byte[4096];
		try {
			while ((byteRead = is.read(buffer)) != -1) {
				output.append(new String(buffer, 0, byteRead));
			}
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return output.toString();
	}
	
	public static void copy(InputStream is, String path) {
		copy(is, path, null);
	}
	
	public static void copy(InputStream is, String path, IProgress callback) {
		if (is == null) return;
		File file = new File(path);
		File parent = file.getParentFile();
		if (!parent.exists()) parent.mkdirs();
		try {
			BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file));
			int byteRead = 0;
			byte[] buffer = new byte[4096];
			int totalByteRead = 0;
			while((byteRead = is.read(buffer)) != -1) {
				os.write(buffer, 0, byteRead);
				totalByteRead += byteRead;
				if (callback != null) {
					callback.onPostProgress(totalByteRead);
				}
			}
			is.close();
			os.flush();
			os.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
	
}
